<template>
  <el-dialog
    v-dialogDrag
    :title="title"
    :visible.sync="dialogVisible"
    class="dialogStyleMiddle"
    :before-close="handleClose"
    append-to-body
  >
    <div>
      <el-form ref="form" v-if="dialogVisible" :model="form" label-width="80px" class="dialog-form">
        <el-row>
          <el-col :span="10">
            <el-form-item label="用户名称">
              <label slot="label">用户名称</label>
              <el-input v-model="form.userName" placeholder="请输入用户名称" size="medium" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="10" class="formHeight">
            <el-form-item label="部门名称" prop="deptId">
              <treeselect
                v-model="form.deptId"
                :options="deptOptions"
                :searchable="true"
                :normalizer="normalizer"
                placeholder="请选择部门"
                no-options-text="暂无数据"
                clear-value-text=""
                :disable-branch-nodes="true"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row
        :gutter="10"
        class="button-wrap"
      >
        <el-col :span="1.5">
          <el-button v-clickForbidden icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button v-clickForbidden icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-col>
        <!-- <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-thumb" size="mini">{{ choice }}</el-button>
        </el-col> -->
      </el-row>
      <el-table
        ref="multipleTable"
        :data="tableData"
        stripe
        class="table-list"
        max-height="330"
        :row-key="getRowKeys"
        :row-style="rowClass"
        size="mini"
        @selection-change="handleSelectionChange"
        @row-click="rowChecked"
      >
        <el-table-column
          type="selection"
          width="38"
          :reserve-selection="true"
        />
        <el-table-column
          prop="loginName"
          label="登录账号"
          align="center"
          min-width="150"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          prop="userName"
          label="用户名称"
          align="center"
          min-width="150"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          prop="dept.deptName"
          label="部门名称"
          min-width="180"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="状态" align="center" prop="status" min-width="60" :formatter="statusFormat" :show-overflow-tooltip="true" />
        <el-table-column
          prop="phonenumber"
          label="电话号码"
          min-width="150"
          :show-overflow-tooltip="true"
        />
      </el-table>
      <!-- 分页-->
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="form.pageNum"
        :limit.sync="form.pageSize"
        :page-sizes="[8,15,20,50,100]"
        :page-count="form.pageCount"
        @pagination="getList"
      />
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button size="medium" @click="handleClose">取 消</el-button>
      <el-button size="medium" type="primary" @click="submitForm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
// 获取部门菜单树
import { selectAllEnterpDeptTree } from '@/api/system/dept'
// 引入用户列表
import { listAllUser } from '@/api/system/user'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  components: {
    Treeselect
  },
  data() {
    return {
      // 高亮数组
      selectRow: [],
      // 弹框标题
      title: '',
      // 弹框标识
      dialogVisible: false,
      // 表格数据 start
      // 分页总页数
      total: 0,
      // 表格数据
      tableData: undefined,
      // 多选框选中数组
      multipleSelection: [],
      // 搜索框 start
      // form数据
      form: {
        pageNum: 1,
        pageSize: 8,
        pageCount: 5,
        deptId: null,
        userName: '',
        status: ''
      },
      name: [],
      // 部门
      dept: [],
      // 创建时间数组
      dateRange: [],
      // 部门树数组
      deptOptions: [],
      normalizer(node) {
        // 去掉children=[]的children属性
        if (node.children && !node.children.length) {
          delete node.children
        }
        return {
          id: node.deptId,
          label: node.deptName,
          children: node.children
        }
      },
      // 状态数据字典
      statusOptions: [],

      // 人员选中start
      // 分页记录功能
      getRowKeys(row) {
        return row.userId
      },
      // 被选中用户id数组
      userIds: [],
      // 用于存储分页回显的数据
      echoIds: [],
      userName: '',
      // 单选,多选
      choice: '多选',
      ids: [],
      echoList: []
    }
  },
  created() {
    // 状态
    this.getDicts('sys_normal_disable').then(response => {
      this.statusOptions = response.data.rows
    })
  },
  methods: {
    // 搜索方法  start
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    // 从父组件获取参数的方法
    handleAdd(title, checkStatus, echoIds, echoList) {
      this.dialogVisible = true
      this.title = title
      this.selectRow = []
      this.handleChoice(checkStatus)
      this.echoIds = echoIds
      this.echoList = echoList
      if (echoIds instanceof Array) {
        this.echoIds = echoIds
      } else if (echoIds != null && echoIds !== '') {
        this.echoIds = echoIds.split(',')
      } else {
        this.echoIds = null
      }
      this.echoList = echoList
      // 用于存储被选中的用户id数组
      this.userIds = []
      this.name = []
      this.dept = []
      this.selectDeptTree()
      this.getList()
    },
    // 表格start
    // 获取用户列表
    getList() {
      if (this.multipleSelection.length) {
        this.echoIds = this.checkIdTemplate(this.multipleSelection)
      }
      listAllUser(this.changeDateRange(this.form, this.dateRange)).then(resp => {
        if (resp) {
          this.tableData = resp.data.rows
          this.total = resp.data.total
          this.$nextTick(() => {
            this.rowMultipleChecked()
          })
        } else {
          this.msgError(resp.message)
        }
      })
    },
    /**
     * 用于数据回显
     * echoIds 用于单个回显
     */
    rowMultipleChecked() {
      if (this.echoIds != null) {
        this.tableData.forEach((item, i) => {
          this.echoIds.forEach((multItem, j) => {
            if (this.tableData[i].userId === this.echoIds[j]) {
              this.$refs.multipleTable.toggleRowSelection(this.tableData[i], true)// 这步操作是让  页面显示选中的数据
            }
          })
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
      // if (this.echoIds != null) { // 这里我先判断从后台查的与会人员id的集合有没有 不然下面length属性会报错。
      //   for (let j = 0; j < this.echoIds.length; j++) { // 这里我用到了双重for循环 this.pageUser这是所有人员信息
      //     for (let i = 0; i < this.tableData.length; i++) {
      //       if (this.echoIds[j] === this.tableData[i].userId) {
      //         if (this.$refs.multipleTable !== undefined) { // 解决下面用bkUserTable不报错 bkUserTable我是在table ref定义的
      //           this.$refs.multipleTable.toggleRowSelection(this.tableData[i], true)// 这个就是回显的核心
      //         }
      //       }
      //     }
      //   }
      // } else {
      //   this.$refs.multipleTable.toggleRowSelection()
      // }
    },
    // 关闭弹框
    handleClose() {
      this.dialogVisible = false
      this.$refs.multipleTable.clearSelection()
      this.emptyForm()
    },
    // 搜索方法
    handleQuery() {
      this.form.pageNum = 1
      this.getList()
    },
    emptyForm() {
      this.form.userName = ''
      this.form.deptId = null
      this.form.status = '0'
      this.dateRange = []
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.emptyForm()
      this.resetForm('form')
      this.handleQuery()
      this.echoIds = null
    },
    /** 清空按钮操作 */
    resetEmpty() {
      this.emptyForm()
      this.resetForm('form')
      this.handleQuery()
    },
    // 部门选择树列表
    selectDeptTree() {
      selectAllEnterpDeptTree().then(resp => {
        if (resp) {
          this.deptOptions = resp.data
        } else {
          this.msgError(resp.message)
        }
      })
    },
    // 控制表格选框多选单选
    handleChoice(checkStatus) {
      if (checkStatus === '0') {
        this.choice = '单选'
        // this.$refs.multipleTable.clearSelection()
      } else {
        this.choice = '多选'
      }
    },
    // 多选框选中事件
    handleSelectionChange(val) {
      this.multipleSelection = val
      // 单选
      if (this.choice === '单选') {
        if (val.length > 1) {
          this.$refs.multipleTable.clearSelection()
          this.$refs.multipleTable.toggleRowSelection(val.pop())
        }
        if (this.multipleSelection.length === 1) {
          this.isStatusShow = this.multipleSelection[0].visible
        }
      }
      // 高亮
      this.selectRow = []
      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach((item, index) => {
          this.selectRow.push(this.tableData.indexOf(item))
        })
      }
      this.checkIds()
    },
    // 高亮样式
    rowClass({ row, rowIndex }) {
      if (this.selectRow.includes(rowIndex)) {
        return { 'background-color': 'rgba(185,221,249,.75)' }
      }
    },
    // 获取选中的行数并且把值返回到父节点（roleDataScopeDet）
    checkIds() {
      this.userIds = []
      this.name = []
      this.dept - []
      for (var i = 0; i < this.multipleSelection.length; i++) {
        this.userIds.push(this.multipleSelection[i].userId)
        this.name.push(this.multipleSelection[i].userName)
        this.dept.push(this.multipleSelection[i].dept.deptName)
      }
    },
    // 点击行时,选框选中
    rowChecked(row) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    // 确定按钮
    submitForm() {
      // 调用向父组件传值的方法
      this.checkIds()
      this.dialogVisible = false
      this.$emit('fatherMethod', this.userIds, this.multipleSelection, this.name, this.dept)
      this.$refs.multipleTable.clearSelection()
    }
  }
}
</script>

<style scoped>
  .dialogStyleMiddle .el-dialog .el-select{
    width: 100px;
  }
</style>
